<!-- eslint-disable prettier/prettier -->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
            
          <campus @schoolCampus="searchhandleSchoolCampus" :selectValue="queryParams.schoolCampusId"></campus>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['school:classes:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleBatchAdd"
          v-hasPermi="['school:classes:add']">批量生成</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['school:classes:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['school:classes:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['school:classes:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="classesList"
        @selection-change="handleSelectionChange"
        @header-click="handleCellMouseEnter"
        v-bind:border="showborder"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="班级年份" align="center" prop="classYear" v-if="columns[0].visible" />
        <el-table-column label="班级" align="center" prop="className" v-if="columns[6].visible" />
        <el-table-column label="班级号" align="center" prop="classNum" v-if="columns[1].visible" />
        <el-table-column label="班主任" align="center" prop="teacherName" v-if="columns[2].visible" />
        <el-table-column label="班级别名" align="center" prop="alias" v-if="columns[3].visible" />
        <el-table-column label="所属校区" align="center" prop="campusName" v-if="columns[4].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[5].visible" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['school:classes:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['school:classes:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-form ref="classesFormRef" :model="form" :rules="rules" :label-width="formLabelWidth">
          <campus @schoolCampus="handleSchoolCampus" @schoolCampuslength="handlegetSchoolCampus"
          :selectValue="form.schoolCampusId"></campus>

        <grade @schoolGrade="handleSchoolGrade" :selectValue="form.classYear" :schoolCampusId="form.schoolCampusId">
        </grade>

        <el-form-item label="班级" prop="classNum">
          <el-input-number v-model="form.classNum" :min="1" :max="30" />
        </el-form-item>

        <teacher @schoolTeachers="handleSchoolTeacher" :teacherlabel="teacherlabel" :selectValue="form.teacherId"
          :schoolCampusId="form.schoolCampusId"></teacher>

        <teacher @schoolTeachers="handleSchoolClassTeacher" :teacherlabel="classteacherlabel"
          :selectValue="form.classTeachers" :schoolCampusId="form.schoolCampusId" :multiple="true"></teacher> 


        <el-row>
          <el-col :span="18">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" :autosize="{ minRows: 3, maxRows: 8 }" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <el-dialog :title="title" v-model="batchopen" width="500px" append-to-body>
      <el-form ref="batchClassesRef" :model="form" :rules="rules" label-width="80px">

        <campus @schoolCampus="handleSchoolCampus" :selectValue="form.schoolCampusId"></campus>


        <div v-for="(grade, year) in grades" :key="year">
          <el-form-item :label="grade" prop="selected">
            <el-select v-model="selected[year]" clearable>
              <el-option v-for="i in 20" :key="i" :value="i">{{ i }} </el-option>
            </el-select>
          </el-form-item>
        </div>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="batchSubmitForm">确 定</el-button>
          <el-button @click="batchopencancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>






  </div>
</template>

<script setup name="Classes" lang="ts">
import {
    listClasses,
    getClasses,
    delClasses,
    addClasses,
    updateClasses,
    getclassesGrade
} from '@/api/school/classes';
import {
        ClassesVO,
        ClassesQuery,
        ClassesForm
} from '@/api/school/classes/types';

import  campus  from '@/components/campus/index.vue'
import { ElForm } from 'element-plus';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const classesList = ref<ClassesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const formLabelWidth = '120px';
const showborder = ref(false)
const grades = ref<Record<string, number | undefined>>({})
const selected = ref<Record<string, number | undefined>>({})
const title = ref('')
const batchopen = ref(false);
const open = ref(false);
const queryFormRef = ref<ElFormInstance>();
const classesFormRef = ref<ElFormInstance>();
const schoolCampuslength = ref<number | null>(null); // 定义用于保存校区数量或其他数值
const teacherlabel = ref("班主任")
const classteacherlabel = ref("任教老师")
const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: ClassesForm = {
  classYear: undefined,
  classNum: undefined,
  teacherId: undefined,
  alias: undefined,
  schoolCampusId: undefined,
  remark: undefined,
  classdata: {},
  classTeachers: [],
  teacherName:'',

}
const data = reactive<PageData<ClassesForm, ClassesQuery>>({
    form: {...initFormData},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
                        classYear: undefined,
                        classNum: undefined,
                        teacherId: undefined,
                        alias: undefined,
                        schoolCampusId: undefined,
                        classTeachers: [],
                        teacherName: '',
        params: {
        }
    },
    rules: {          classYear: [
                       {
                         required: true, message: "班级不能为空", trigger: "blur" }
                    ], classNum: [
                        {
                            required: true, message: "班级号不能为空", trigger: "blur" }
                    ], schoolCampusId: [
                        {
                            required: true, message: "所属校区不能为空", trigger: "blur" }
                    ]
    }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询班级管理列表 */
const getList = async () => {
    loading.value = true;
    const res = await listClasses(queryParams.value);
        classesList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
        classesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ClassesVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加班级管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ClassesVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    console.log("修改项id",_id)
    const res = await getClasses(_id);
    console.log("修改项",res.data)
    dialog.visible = true;
    dialog.title = "修改班级管理";
    Object.assign(form.value, res.data);
}


/** 提交按钮 */
const submitForm = () => {
        classesFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            console.log("提交表单",form.value)
            if (form.value.id) {
                await updateClasses(form.value).finally(() =>  buttonLoading.value = false);
            } else {
                await addClasses(form.value).finally(() =>  buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ClassesVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除班级管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delClasses(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
    proxy?.download('school/classes/export', {
        ...queryParams.value
    }, `classes_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
    getList();
});


/** 列信息 */
const columns = ref([
            {key: 0, label: `班级年份`, visible: true},
            {key: 1, label: `班级号`, visible: true},
            {key: 6, label: `班级`, visible: true},
            {key: 2, label: `班主任id`, visible: true},
            {key: 3, label: `班级别名`, visible: true},
            {key: 4, label: `所属校区`, visible: true},
            {key: 5, label: `备注`, visible: true},
]);

/** 新增按钮操作 */
function handleBatchAdd() {

  reset();
  batchopen.value = true;
  title.value = "批量添加班级";

}



function handleCellMouseEnter() {
    showborder.value = !showborder.value;
}



/** 提交按钮 */
function batchSubmitForm() {
  // 提交动态创建的班级数据 ，封装成map 提交到后台
  let map = new Map();
  let adata = Object.keys(grades.value);
  for (let k of adata) {
    if (selected.value[k] !== undefined) {
      map.set(k, selected.value[k])
    }
  }


  console.log(map);
  console.log(Object.fromEntries(map));

  data.form.classdata = Object.fromEntries(map);

  const batchClassesRef = proxy?.$refs["batchClassesRef"] as InstanceType<typeof ElForm> | undefined;
  if (!batchClassesRef) {
    proxy?.$modal.msgError("表单未正确初始化");
    return;
  }

  batchClassesRef.validate((valid: any) => {
    if (valid) {
      addClasses(form.value).then(response => {
        proxy?.$modal.msgSuccess("新增成功");
        open.value = false;
        batchopen.value = false;
        getList();
      }).catch(() => {
        getList();
      });
    }
  });
}

function handlegetSchoolCampus(value: number|null) {
  schoolCampuslength.value = value;
}
function searchhandleSchoolCampus(value: string | number |undefined) {
  console.log("searchhandleSchoolCampus",value);
   data.queryParams.schoolCampusId = value;
}

/**
 * 从 campus组件中获取校区
 * @param {*} value
 */
function handleSchoolCampus(value: string | number) {
  console.log("handleSchoolCampus",value);

  // 修复：使用 ?? 将 null/undefined 转换为 undefined
  data.form.schoolCampusId = value ;

  if (value !== null) {
    getGrade();
  }
}

function getGrade() {
  if(data.form.schoolCampusId != undefined){
    getclassesGrade(data.form.schoolCampusId).then(response => {
      console.log(response.data);
      grades.value = response.data;
    });
  }
}

function batchopencancel() {
  batchopen.value = false;
}

function handleSchoolGrade(value: number|undefined) {
  data.form.classYear = value;
}

function handleSchoolTeacher(value: string|number|undefined) {
  data.form.teacherId = value;
  if (value != 0 && value != undefined) {
    if (data.form.classTeachers != undefined) {
      let teachers = data.form.classTeachers;
      data.form.classTeachers = teachers.filter(i => i != value)
    }
  }
}

function handleSchoolClassTeacher(value: any) {
  data.form.classTeachers = value == null?null:value;
if (value !== null && value.length > 0) {
  if (typeof data.form.teacherId === 'string') {
    const teachers = value;
    if (teachers.includes(data.form.teacherId)) {
      data.form.teacherId = '';
    }
  }
}
}
</script>
